package net.crazyblock.mobilesafe;

import java.util.ArrayList;
import java.util.List;

import net.crazyblock.mobilesafe.AppManagerActivity.ViewHolder;
import net.crazyblock.mobilesafe.domain.TaskInfo;
import net.crazyblock.mobilesafe.engin.TaskInfoProvider;
import net.crazyblock.mobilesafe.utils.SystemInfoUtils;
import android.app.Activity;
import android.app.ActivityManager;
import android.graphics.Color;
import android.os.Bundle;
import android.text.format.Formatter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class TaskManagerActivity extends Activity {
	private TextView tv_process_count;
	private TextView tv_mem_info;
	private LinearLayout ll_loading;
	private ListView lv_task_manager;
	private List<TaskInfo> allTaskInfos;
	private List<TaskInfo> userTaskInfos;
	private List<TaskInfo> sysTaskInfos;
	private TextView tv_status;
	private TaskManagerAdapter adapter;
	private int processCount;
	private long availMem;
	private long totalMem;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_task_manager);
		tv_process_count = (TextView) findViewById(R.id.tv_process_count);
		tv_mem_info = (TextView) findViewById(R.id.tv_men_info);
		ll_loading = (LinearLayout) findViewById(R.id.loading);
		lv_task_manager = (ListView) findViewById(R.id.lv_task_infos);
		fillData();
		tv_status = (TextView) findViewById(R.id.tv_statue);
		lv_task_manager.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				if (userTaskInfos != null && sysTaskInfos != null) {
					tv_status.setVisibility(View.VISIBLE);
					if (firstVisibleItem > userTaskInfos.size()) {
						tv_status.setText("系统进程：" + sysTaskInfos.size() + "个");
					} else {
						tv_status.setText("用户进程：" + userTaskInfos.size() + "个");
					}
				}

			}
		});
		lv_task_manager.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				TaskInfo taskInfo;
				if (position == 0) {
					return;
				} else if (position == userTaskInfos.size() + 1) {
					return;
				} else if (position < userTaskInfos.size() + 1) {
					int newPosition = position - 1;
					taskInfo = userTaskInfos.get(newPosition);
				} else {
					int newPosition = position - userTaskInfos.size() - 2;
					taskInfo = sysTaskInfos.get(newPosition);
				}
				if (getPackageName().equals(taskInfo.getPackName())) {
					return;
				}
				ViewHolder holder = (ViewHolder) view.getTag();
				if (taskInfo.isChecked()) {
					taskInfo.setChecked(false);
					holder.cb_status.setChecked(false);
				} else {
					taskInfo.setChecked(true);
					holder.cb_status.setChecked(true);
				}
			}
		});
	}

	private void setTitle() {
		int processCount = SystemInfoUtils.getRunningProcessCount(this);
		tv_process_count.setText("运行中的进程：" + processCount + "个");
		availMem = SystemInfoUtils.getAvailMem(this);
		totalMem = SystemInfoUtils.getTotalMem(this);
		tv_mem_info.setText("剩余/总内存："
				+ Formatter.formatFileSize(this, availMem) + "/"
				+ Formatter.formatFileSize(this, totalMem));
	}

	private void fillData() {
		ll_loading.setVisibility(View.VISIBLE);
		new Thread() {
			public void run() {
				allTaskInfos = TaskInfoProvider
						.getTaskInfos(TaskManagerActivity.this);
				userTaskInfos = new ArrayList<TaskInfo>();
				sysTaskInfos = new ArrayList<TaskInfo>();
				for (TaskInfo info : allTaskInfos) {
					if (info.isUserTask()) {
						userTaskInfos.add(info);
					} else {
						sysTaskInfos.add(info);
					}
				}
				runOnUiThread(new Runnable() {
					public void run() {
						if (adapter != null) {
							adapter.notifyDataSetChanged();
						} else {
							adapter = new TaskManagerAdapter();
							lv_task_manager.setAdapter(adapter);
						}
						ll_loading.setVisibility(View.INVISIBLE);
						setTitle();
					}
				});
			};
		}.start();
	}

	private class TaskManagerAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return allTaskInfos.size() + 2;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TaskInfo taskInfo;
			if (position == 0) {
				TextView tv = new TextView(TaskManagerActivity.this);
				tv.setBackgroundColor(Color.GRAY);
				tv.setTextColor(Color.WHITE);
				tv.setTextSize(20);
				tv.setText("用户进程" + userTaskInfos.size() + "个");
				return tv;
			} else if (position == userTaskInfos.size() + 1) {
				TextView tv = new TextView(TaskManagerActivity.this);
				tv.setBackgroundColor(Color.GRAY);
				tv.setTextColor(Color.WHITE);
				tv.setTextSize(20);
				tv.setText("系统进程" + sysTaskInfos.size() + "个");
				return tv;
			} else if (position < userTaskInfos.size() + 1) {
				int newPosition = position - 1;
				taskInfo = userTaskInfos.get(newPosition);
			} else {
				int newPosition = position - userTaskInfos.size() - 2;
				taskInfo = sysTaskInfos.get(newPosition);
			}
			View view;
			ViewHolder holder;
			// 注意检查converView是不是一个item
			if (convertView != null && convertView instanceof RelativeLayout) {
				view = convertView;
				holder = (ViewHolder) view.getTag();
			} else {

				view = View.inflate(TaskManagerActivity.this,
						R.layout.list_item_taskinfo, null);
				holder = new ViewHolder();
				holder.tv_task_name = (TextView) view
						.findViewById(R.id.tv_task_name);
				holder.tv_task_memsize = (TextView) view
						.findViewById(R.id.tv_task_memsize);
				holder.iv_task_icon = (ImageView) view
						.findViewById(R.id.iv_task_icon);
				holder.cb_status = (CheckBox) view.findViewById(R.id.cb_status);
				view.setTag(holder);
			}
			holder.iv_task_icon.setImageDrawable(taskInfo.getIcon());
			holder.tv_task_name.setText(taskInfo.getName());
			holder.tv_task_memsize.setText("内存占用："
					+ Formatter.formatFileSize(TaskManagerActivity.this,
							taskInfo.getMemSize()));
			holder.cb_status.setChecked(taskInfo.isChecked());
			if (getPackageName().equals(taskInfo.getPackName())) {
				holder.cb_status.setVisibility(View.INVISIBLE);
			}else {
				holder.cb_status.setVisibility(View.VISIBLE);
			}
			return view;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

	}

	static class ViewHolder {
		TextView tv_task_name;
		TextView tv_task_memsize;
		ImageView iv_task_icon;
		CheckBox cb_status;

	}

	/**
	 * 选中全部
	 * 
	 * @param view
	 */
	public void selectAll(View view) {
		for (TaskInfo info : allTaskInfos) {
			if (getPackageName().equals(info.getPackName())) {
				continue;
			}
			info.setChecked(true); 
		}
		adapter.notifyDataSetChanged();
	}

	/**
	 * 选中相反的
	 * 
	 * @param view
	 */
	public void selectOppo(View view) {
		for (TaskInfo info : allTaskInfos) {
			if (getPackageName().equals(info.getPackName())) {
				continue;
			}
			info.setChecked(!info.isChecked());
		}
		adapter.notifyDataSetChanged();
	}

	/**
	 * 一键清理
	 * 
	 * @param view
	 */
	public void killAll(View view) {
		ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
		int count = 0;
		long savedMem = 0;
		// 记录那些被杀死的条目
		List<TaskInfo> killedTaskinfos = new ArrayList<TaskInfo>();
		for (TaskInfo info : allTaskInfos) {
			if (info.isChecked()) {// 被勾选的，杀死这个进程。
				am.killBackgroundProcesses(info.getPackName());
				if (info.isUserTask()) {
					userTaskInfos.remove(info);
				} else {
					sysTaskInfos.remove(info);
				}
				killedTaskinfos.add(info);
				count++;
				savedMem += info.getMemSize();
			}
		}
		allTaskInfos.removeAll(killedTaskinfos);
		adapter.notifyDataSetChanged();
		Toast.makeText(this,"杀死了" + count + "个进程，释放了"+ Formatter.formatFileSize(this, savedMem) + "的内存", 1).show();
		processCount -= count;
		availMem += savedMem;
		tv_process_count.setText("运行中的进程：" + processCount + "个");
		tv_mem_info.setText("剩余/总内存："
				+ Formatter.formatFileSize(this, availMem) + "/"
				+ Formatter.formatFileSize(this, totalMem));
	}

	/**
	 * 进入设置
	 * 
	 * @param view
	 */
/*	public void enterSetting(View view) {
		Intent intent = new Intent(this, TaskSettingActivity.class);
		startActivityForResult(intent, 0);
	}*/

}
